package com.merry.jcip;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author zouyb
 * 使用ThreadLocal轻松实现线程封闭
 */
public class ThreadLocalTest {

    /**
     * 新建了一个泛型为Connection的ThreadLocal对象，并且重写了ThreadLocal的initialValue方法，让其返回一个connection连接。
     */
    private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>(){
        @Override
        public Connection initialValue(){
            Connection connection=null;
            try {
                connection=DriverManager.getConnection("DB_URL");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return connection;
        }
    };

    public static Connection getConnection(){
        return connectionHolder.get();
    }
}
